<template>
  <div class="map-container">
    <div ref="mapRef" class="map-wrapper"></div>
    <div class="controls">
      <el-button @click="startDrawCircle" :disabled="isDrawing"
        >绘制圆形</el-button
      >
      <el-button @click="clearDrawings" :disabled="!hasDrawings"
        >清除绘制</el-button
      >
    </div>

    <div v-if="selectedArea" class="area-info">
      <p><strong>地区:</strong> {{ selectedArea.region }}</p>
      <p>
        <strong>面积:</strong> {{ formatNumber(selectedArea.area) }} 平方米 (约
        {{ (selectedArea.area / 666.67).toFixed(2) }} 亩)
      </p>
      <p>
        <strong>中心点:</strong> [{{ selectedArea.center[0].toFixed(6) }},
        {{ selectedArea.center[1].toFixed(6) }}]
      </p>
      <p><strong>半径:</strong> {{ selectedArea.radius }} 米</p>
      <p><strong>边界范围:</strong> {{ selectedArea.bounds }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from "vue";
import { ElMessage, ElButton } from "element-plus";

// 地图相关引用
const mapRef = ref<HTMLDivElement | null>(null);
let mapInstance: AMap.Map | null = null;
let currentCircle: AMap.Circle | null = null;
let isDrawing = ref(false);
let hasDrawings = ref(false);
let startPoint: AMap.LngLat | null = null;

// 选中区域信息
const selectedArea = ref<{
  region: string;
  area: number;
  radius: number;
  center: [number, number];
  bounds: string;
} | null>(null);

// 组件属性
interface Props {
  center: [number, number]; // [经度, 纬度]
  zoom: number;
}

const props = withDefaults(defineProps<Props>(), {
  center: () => [116.397428, 39.90923], // 默认北京
  zoom: 13,
});

// 组件事件
const emit = defineEmits<{
  "circle-selected": (circle: {
    region: string;
    area: number;
    radius: number;
    center: [number, number];
    bounds: string;
  }) => void;
  "draw-cleared": () => void;
}>();

// 格式化数字显示
const formatNumber = (num: number): string => {
  return num.toLocaleString("zh-CN", { maximumFractionDigits: 2 });
};

// 初始化地图
const initMap = async () => {
  if (!mapRef.value || !window.AMap) return;

  try {
    // 创建地图实例
    mapInstance = new window.AMap.Map(mapRef.value, {
      center: props.center,
      zoom: props.zoom,
      viewMode: "3D",
      resizeEnable: true,
    });

    // 加载所需插件
    await new Promise((resolve, reject) => {
      window.AMap.plugin(["AMap.Geocoder"], (plugins) => {
        if (plugins) {
          resolve(plugins);
        } else {
          reject(new Error("插件加载失败"));
        }
      });
    });

    console.log("地图初始化成功");
    return true;
  } catch (error: unknown) {
    console.error("地图初始化失败:", error);
    ElMessage.error("地图加载失败，请检查网络或Key");
    return false;
  }
};

// 开始绘制圆形
const startDrawCircle = () => {
  if (!mapInstance) return;

  // 清除现有圆形
  if (currentCircle) {
    clearDrawings();
  }

  isDrawing.value = true;
  ElMessage.info("请在地图上点击确定圆心，拖动确定半径");

  // 鼠标点击事件 - 确定圆心
  const onMapClick = (e: { lnglat: AMap.LngLat }) => {
    if (!startPoint) {
      // 记录起始点（圆心）
      startPoint = e.lnglat;

      // 创建初始圆形
      currentCircle = new window.AMap.Circle({
        center: startPoint,
        radius: 100, // 初始半径
        strokeColor: "#FF0000",
        strokeWeight: 2,
        fillColor: "#FFCCCC",
        fillOpacity: 0.5,
      });

      // 监听鼠标移动事件 - 调整半径
      mapInstance.on("mousemove", onMouseMove);

      // 监听鼠标抬起事件 - 完成绘制
      mapInstance.once("mouseup", onMouseUp);
    }
  };

  // 鼠标移动事件 - 动态调整半径
  const onMouseMove = (e: { lnglat: AMap.LngLat }) => {
    if (currentCircle && startPoint) {
      // 计算两点之间的距离（米）作为半径
      const radius = startPoint.distance(e.lnglat);
      currentCircle.setRadius(radius);
    }
  };

  // 鼠标抬起事件 - 完成绘制
  const onMouseUp = () => {
    if (currentCircle && startPoint) {
      isDrawing.value = false;
      hasDrawings.value = true;

      // 移除临时事件监听
      mapInstance!.off("mousemove", onMouseMove);

      // 获取圆形信息
      const radius = currentCircle.getRadius();
      const center = [startPoint.getLng(), startPoint.getLat()] as [
        number,
        number
      ];

      // 计算面积和区域信息
      calculateCircleInfo(currentCircle, center, radius);

      ElMessage.success("圆形绘制完成");
    }

    // 重置起始点
    startPoint = null;
    // 移除点击事件
    mapInstance!.off("click", onMapClick);
  };

  // 绑定点击事件
  mapInstance.once("click", onMapClick);
};

// 计算圆形信息
const calculateCircleInfo = (
  circle: AMap.Circle,
  center: [number, number],
  radius: number
) => {
  if (!mapInstance) return;

  // 计算圆形面积 (πr²)
  const area = Math.PI * Math.pow(radius, 2);

  // 获取边界范围
  const bounds = getCircleBounds(circle);

  // 获取地址信息
  const geocoder = new window.AMap.Geocoder();
  geocoder.getAddress(
    new window.AMap.LngLat(center[0], center[1]),
    (status, result) => {
      if (status === "complete" && result.regeocode) {
        const { province, city, district, township } =
          result.regeocode.addressComponent;
        const region = [province, city, district, township]
          .filter(Boolean)
          .join("");

        selectedArea.value = {
          region,
          area,
          radius,
          center,
          bounds: `西南角: [${bounds.sw[0].toFixed(6)}, ${bounds.sw[1].toFixed(
            6
          )}], 东北角: [${bounds.ne[0].toFixed(6)}, ${bounds.ne[1].toFixed(
            6
          )}]`,
        };

        // 触发事件
        emit("circle-selected", selectedArea.value);
      } else {
        ElMessage.error("获取地区信息失败");
        // 即使获取地址失败，也展示其他信息
        selectedArea.value = {
          region: "未知区域",
          area,
          radius,
          center,
          bounds: `西南角: [${bounds.sw[0].toFixed(6)}, ${bounds.sw[1].toFixed(
            6
          )}], 东北角: [${bounds.ne[0].toFixed(6)}, ${bounds.ne[1].toFixed(
            6
          )}]`,
        };
      }
    }
  );
};

// 获取圆形边界范围
const getCircleBounds = (
  circle: AMap.Circle
): {
  sw: [number, number];
  ne: [number, number];
  center: [number, number];
} => {
  const center = circle.getCenter().toArray() as [number, number];
  const radius = circle.getRadius();

  // 计算经纬度范围 (1度 ≈ 111319.5米)
  const latDegree = radius / 111319.5;
  const lngDegree = radius / (111319.5 * Math.cos((center[1] * Math.PI) / 180));

  return {
    sw: [center[0] - lngDegree, center[1] - latDegree],
    ne: [center[0] + lngDegree, center[1] + latDegree],
    center,
  };
};

// 清除绘制
const clearDrawings = () => {
  if (currentCircle) {
    currentCircle.remove();
    currentCircle = null;
  }

  selectedArea.value = null;
  isDrawing.value = false;
  hasDrawings.value = false;
  startPoint = null;

  // 移除可能残留的事件监听
  if (mapInstance) {
    mapInstance.off("mousemove", () => {});
    mapInstance.off("click", () => {});
  }

  ElMessage.success("已清除所有绘制");
  emit("draw-cleared");
};

// 组件生命周期
onMounted(async () => {
  await nextTick();
  await initMap();
});

onUnmounted(() => {
  if (mapInstance) {
    mapInstance.destroy();
    mapInstance = null;
  }
  clearDrawings();
});

// 监听属性变化，更新地图中心
watch(
  () => props.center,
  (newCenter) => {
    if (mapInstance) {
      mapInstance.setCenter(newCenter);
    }
  }
);

watch(
  () => props.zoom,
  (newZoom) => {
    if (mapInstance) {
      mapInstance.setZoom(newZoom);
    }
  }
);
</script>

<style scoped>
.map-container {
  position: relative;
  width: 600px;
  height: 200px;
  min-height: 200px;
}

.map-wrapper {
  width: 100%;
  height: 100%;
}

.controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  display: flex;
  gap: 10px;
}

.area-info {
  position: absolute;
  top: 60px;
  left: 10px;
  z-index: 10;
  background: white;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 350px;
}

.area-info p {
  margin: 6px 0;
  font-size: 14px;
}

/* 禁用状态样式 */
:deep(.el-button.is-disabled) {
  opacity: 0.7;
}
</style>
